import hashlib 
import base64
import datetime
import json
from django.conf import settings

class MyJWT(object):
    ERROE = ""
    SECRET_DICT = {
        'sha256':hashlib.sha256,
        'md5':hashlib.md5,
        'sha1':hashlib.sha1
    }

    def __init__(self,key=settings.JWT_KEY , secret='sha256'):
        self.key = key
        self.header = {
            "alg": secret,
            "typ": "JWT"
        }
        self.secret_obj = MyJWT.SECRET_DICT[secret]

    def encode(self,payload,expire=600):
        payload['expire'] = (datetime.datetime.now() + datetime.timedelta(seconds=expire)).strftime('%Y%m%d%H%M%S')
        payload = json.dumps(payload)
        base64_header = base64.b64encode(str(self.header).encode())
        base64_payload = base64.b64encode(str(payload).encode())
        secret_obj = self.secret_obj()
        secret_obj.update((str(self.header)+str(payload)+self.key).encode())
        sign = secret_obj.hexdigest()
        return base64_header.decode() +'.' + base64_payload.decode() + '.' +sign

    def decode(self,jwt_str):
        jwt_list = jwt_str.split('.')
        header = base64.b64decode(jwt_list[0]).decode()
        payload = base64.b64decode(jwt_list[1]).decode()
        now = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
        secret_obj = self.secret_obj()
        secret_obj.update((header+payload+self.key).encode())
        sign = secret_obj.hexdigest()
        payload = json.loads(payload)
        if int(now) > int(payload['expire']):
            return False, "token expire"
        elif sign != jwt_list[2]:
            return False, 'Authentication failed'
        else:
            return True,payload


if __name__ == '__main__':
    import time
    my = MyJWT('adf')
    data = {
        'username':"www"
    }
    jwt = my.encode(data,4)
    print(my.decode(jwt))

    time.sleep(3)
    print(my.decode(jwt))